package com.ricky.base.exception;

import com.ricky.base.enums.ResultEnum;
import com.ricky.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;

/**
 * @Author Ricky
 * @Date 2024/6/20 14:08
 * @Description: 自定义异常类接口
 */
@RestControllerAdvice
@Order(-1000)
public class ControllerAdviceProcessor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected MessageSource messageSource;

    @ExceptionHandler({RuntimeException.class})
    public Object handleException(RuntimeException ex) {

        // 打印出错误发生的位置

        StackTraceElement[] stackTrace = ex.getStackTrace();
        String stackTraceString = Arrays.toString(stackTrace);
        System.out.println("异常发生的位置: " + stackTraceString);
        logger.error("异常发生的位置: " + stackTraceString);
        String msgCode = ex.getMessage();
        try {
            Integer code = Integer.parseInt(msgCode);
            logger.error(ex.toString()+ ResultEnum.getByKey(code).getMsg());
            return AjaxResult.error(ResultEnum.getByKey(code).getMsg());
        } catch (Exception e) {
            logger.error(ex.toString());
            if (ex.getMessage() == null) {
                return AjaxResult.error(ex.toString());
            } else {
                return AjaxResult.error(ex.getMessage());
            }
        }
    }

}
